package com.cyzy.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.cyzy.domain.TAddress;
import com.cyzy.dto.ResponseData;
import com.cyzy.service.TAddressService;
import com.cyzy.mapper.TAddressMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * @author 10204
 * @description 针对表【t_address】的数据库操作Service实现
 * @createDate 2024-11-26 00:47:45
 */
@Service
public class TAddressServiceImpl extends ServiceImpl<TAddressMapper, TAddress> implements TAddressService {
    @Autowired
    private TAddressMapper tAddressMapper;

    @Override
    public ResponseData addAddress(TAddress address) {
        QueryWrapper<TAddress> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_id", address.getUserId())
                .eq("province_city_district", address.getProvinceCityDistrict())
                .eq("full_address", address.getFullAddress())
                .eq("username", address.getUsername())
                .eq("userphone", address.getUserphone())
                .eq("default_address", address.getDefaultAddress());

        // 检查是否存在相同的地址
        TAddress existingAddress = tAddressMapper.selectOne(queryWrapper);
        if (existingAddress != null) {
            return ResponseData.no2("地址已存在");
        }

        if (address.getDefaultAddress() != null && address.getDefaultAddress().equals("0")) {
            // 1. 将当前用户所有地址的 default_address 设置为 1（非默认地址）
            UpdateWrapper<TAddress> updateWrapper = new UpdateWrapper<>();
            updateWrapper.eq("user_id", address.getUserId())
                    .set("default_address", 1); // 设置其他地址为非默认标志 1
            tAddressMapper.update(null, updateWrapper); // 执行更新

            // 2. 设置当前地址为默认地址
            address.setDefaultAddress("0"); // 将当前地址设置为默认地址
        }

        int res = tAddressMapper.insert(address); // 返回插入的行数
        return new ResponseData(200, "success", res, 0);
    }

    @Override
    public ResponseData getAddress(int userId) {
        QueryWrapper queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_id", userId);
        List<TAddress> addressList = tAddressMapper.selectList(queryWrapper);
        return new ResponseData(200, "success", addressList, 0);
    }

    @Override
    @Transactional // 确保方法运行在事务中
    public int updateAddress(TAddress address) {
        int rowsAffected = tAddressMapper.updateById(address);
        if (rowsAffected > 0) {
            // 首先，将该用户所有地址的 DefaultAddress 状态设置为 1（非默认地址）
            LambdaUpdateWrapper<TAddress> resetWrapper = new LambdaUpdateWrapper<>();
            resetWrapper.eq(TAddress::getUserId, address.getUserId())
                    .set(TAddress::getDefaultAddress, "1");
            tAddressMapper.update(null, resetWrapper);
            // 然后，将当前 addressId 的 DefaultAddress 状态设置为 0（默认地址）
            LambdaUpdateWrapper<TAddress> updateWrapper = new LambdaUpdateWrapper<>();
            updateWrapper.eq(TAddress::getAddressId, address.getAddressId())
                    .eq(TAddress::getUserId, address.getUserId())
                    .set(TAddress::getDefaultAddress, "0");
            tAddressMapper.update(null, updateWrapper);
        }
        return rowsAffected;
    }


    @Override
    public int deleteAddress(int addressId, int userId) {
        QueryWrapper<TAddress> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_id", userId);
        queryWrapper.eq("address_id", addressId);
        int result = tAddressMapper.delete(queryWrapper);
        return result;
    }

    @Override
    public int SetAddress(TAddress address) {
        return tAddressMapper.SetAddress(address);
    }

    @Override
    public ResponseData getAddres(String userId) {
        QueryWrapper<TAddress> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_id", userId);
        queryWrapper.eq("Default_Address", "0");
        TAddress existingAddress = tAddressMapper.selectOne(queryWrapper);
        return new ResponseData(200, "success", existingAddress, 0);
    }
}




